﻿using eslib.py;
using Python.Runtime;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace test
{
    internal class PyTest2
    {

        public void fuck(string who)
        {
            Console.WriteLine("delay..");
            Thread.Sleep(2000);
            Console.WriteLine($"{who}被fuck了");
        }




        string code = @"
class Test:
    i=0

    #__init__为构造函数
    def __init__(this,i):
        this.i=i;
        
    def setI(this,i):
        this.i=i

    def getI(this):
        return this.i

    def test(this):
        print(""py test() call."")

t=Test(4569)
t.test()

#调用C#对象
so.fuck(""charme"")

res=t.getI()
";


        internal void test()
        {
            PyRunner py = new PyRunner(code);

            //绑定对象
            var so = new PyTest2();
            py.AddBindObject(nameof(so), so);

            //运行源码或预编译对象
            py.Execute().Wait();
        }
    }



    /// <summary>
    /// 重写PreInit部分预编译脚本
    /// </summary>
    internal class PyRunner : PyEngine
    {
        string code;
        PyObject script;

        PyDict dict = new PyDict();


        public PyRunner(string code)
        {
            this.code = code;
        }



        public override void PreInit()
        {
            //预编译
            script = PyEngine.Compile(code);
        }


        public async Task Execute()
        {
            await Exec(() => script, dict);
        }


        /// <summary>
        /// 释放前引发
        /// </summary>
        /// <param name="scope"></param>
        public override void PreDispose(PyScope scope)
        {
            //从py中取出变量res
            dynamic res = dict["res"];
            Console.WriteLine($"py运行结束,res={res}");
        }


    }

}